package tools;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class CsvToXlsx {
    private static final String RESOURCES_PATH = "src/test/resources/";
    public static void main(String[] args) {
        // 示例调用
        CsvToXlsx csvToXlsx = new CsvToXlsx();
//        csvToXlsx.execute(RESOURCES_PATH + "triangle_robustness.csv",
//                RESOURCES_PATH + "triangle_robustness.xlsx");
        csvToXlsx.execute(RESOURCES_PATH + "triangle_worst_case_boundary_values.csv",
                RESOURCES_PATH + "triangle_worst_case_boundary_values.xlsx");
//        csvToXlsx.execute(RESOURCES_PATH + "triangle_worst_case_robustness_boundary_values.csv",
//                RESOURCES_PATH + "triangle_worst_case_robustness_boundary_values.xlsx");
    }

    void execute(String fileName, String outPutFileName) {
        List<String[]> csvData = new ArrayList<>();
        try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {
            String line;
            Integer index = 0;
            while ((line = br.readLine()) != null) {
                // 只区分最后一个逗号
                int lastCommaIndex = line.lastIndexOf(',');
                if (lastCommaIndex > 0) {
                    String testCase = line.substring(0, lastCommaIndex);
                    String expected = line.substring(lastCommaIndex + 1);
                    // 将“测试编号”和“测试用例”作为两个元素放入数组
                    csvData.add(new String[]{index.toString(),testCase, expected});
                } else {
                    // 如果没有找到逗号，则跳过该行或根据实际情况处理
                    System.err.println("No comma found in line: " + line);
                }
                index++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 创建工作簿和工作表
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        int rowNum = 0;
        for (String[] rowData : csvData) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for (String data : rowData) {
                Cell cell = row.createCell(colNum++);
                cell.setCellValue(data);
            }
        }

        // 自动调整列宽
        for (int i = 0; i < csvData.get(0).length; i++) {
            sheet.autoSizeColumn(i);
        }

        // 写入文件并关闭工作簿
        try (FileOutputStream fileOut = new FileOutputStream(outPutFileName)) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}